<?php

namespace app\admin\controller\shopro\activity;

use addons\shopro\model\User;
use app\common\controller\Backend;
use think\Db;
use addons\shopro\library\Export;
use app\admin\model\shopro\activity\ActivityOrder as ActivityOrderModel;
use app\admin\model\shopro\activity\Activity as ActivityModel;
use app\admin\controller\shopro\Base;
/**
 * 活动报名记录
 *
 * @icon fa fa-circle-o
 */
class activityOrder extends Base
{
    protected $noNeedRight = [];

    /**
     * UserWalletApply模型对象
     * @var \app\admin\model\shopro\UserWalletApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\activity\ActivityOrder;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $activity_id = $this->request->request('id');
            $nobuildfields = ['user_nickname', 'user_mobile'];
            $where_other = ["activity_id" => $activity_id];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);
            $total = $this->buildSearch()
                ->where($where)
                ->where($where_other)
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearch()
                ->with('user')
                ->with('agent')
                ->where($where)
                ->where($where_other)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $activity = ActivityModel::where("id",$activity_id)->find();
            for($i = 0;$i < count($list);$i++){
                $res = ActivityOrderModel::getInfo($list[$i]['user_id'],$activity);
                $res['order_count'] = $activity['order_count'];
                $list[$i] = array_merge($list[$i],$res);
            }
            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }

    public function handle($ids)
    {
        $order = $this->model->where('id',$ids)->find();
        if (!$order) {
            $this->error('未找到该报名记录');
        }
        $operate = $this->request->post('operate');
        Db::startTrans();
        try {
            switch ($operate) {
                case '1':
                    $reward = $this->request->post('reward');
                    $order->status = 2;
                    $order->reward = $reward;
                    User::money($reward, $order->user_id, 'activity_income', $order->id);
                    break;
                case '-1':
                    $order->status = 0;
                    break;
            }
            $order->save();
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功' );
    }

    /**
     * 提现搜索
     *
     * @return object
     */
    public function buildSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $user_nickname = isset($filter['user_nickname']) ? $filter['user_nickname'] : '';
        $user_mobile = isset($filter['user_mobile']) ? $filter['user_mobile'] : '';

        // 当前表名
        $tableName = $this->model->getQuery()->getTable();

        $applys = $this->model;
        
        // 购买人查询
        if ($user_nickname) {
            $applys = $applys->whereExists(function ($query) use ($user_nickname, $user_mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();
                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . '.user_id');

                if ($user_nickname) {
                    $query = $query->where('nickname', 'like', "%{$user_nickname}%");
                }

                if ($user_mobile) {
                    $query = $query->where('mobile', 'like', "%{$user_mobile}%");
                }

                return $query;
            });
        } else if($user_mobile){
            $applys = $applys->whereExists(function ($query) use ($user_mobile, $tableName) {
                $userTableName = (new \app\admin\model\shopro\commission\Agent())->getQuery()->getTable();
                $query = $query->table($userTableName)->where($userTableName . '.user_id=' . $tableName . '.user_id');
                if ($user_mobile) {
                    $query = $query->where('apply_info', 'like', "%{$user_mobile}%");
                }

                return $query;
            });
        }

        return $applys;
    }
}
